package com.qianxx.base.widget;

import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.qianxx.draw.R;
import com.qianxx.base.loading.LoadingView;
import com.qianxx.base.utils.LogUtil;


/**
 * 继承自SwipeRefreshLayout,从而实现滑动到底部时上拉加载更多的功能.
 */
public class RefreshLayout extends SwipeRefreshLayout implements
		OnScrollListener {

	private Context mContext;

	/**
	 * loading指示控件(上拉加载时显示)
	 */
	private LoadingView mRefreshLoading;
	private View layFooter;
	private TextView tvLoadMore;

	/**
	 * 滑动到最下面时的上拉操作
	 */

	private int mTouchSlop;
	/**
	 * listview实例
	 */
	private ListView mListView;

	/**
	 * 上拉监听器, 到了最底部的上拉加载操作
	 */
	private OnLoadListener mOnLoadListener;

	/**
	 * ListView的加载中footer
	 */
	private View mListViewFooter;

	/**
	 * 按下时的y坐标
	 */
	private int mYDown;
	/**
	 * 抬起时的y坐标, 与mYDown一起用于滑动到底部时判断是上拉还是下拉
	 */
	private int mLastY;
	/**
	 * 是否在加载中 ( 上拉加载更多 )
	 */
	private boolean isLoading = false;

	public RefreshLayout(Context context) {
		this(context, null);
		this.mContext = context;
	}

	public RefreshLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
	}

	public void initLayFooter(ListView listView, Context context) {
		mListViewFooter = LayoutInflater.from(context).inflate(
				R.layout.base_lay_loadmore, null, false);
		this.mListView = listView;

		mListView.addFooterView(mListViewFooter);
		layFooter = mListViewFooter.findViewById(R.id.layFooter);
		mRefreshLoading = (LoadingView) mListViewFooter
				.findViewById(R.id.refreshLoading);
		tvLoadMore = (TextView) mListViewFooter.findViewById(R.id.tvLoadMore);
		tvLoadMore.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				loadData(); // 点击也可以触发加载
			}
		});
	}

	// @Override
	// protected void onLayout(boolean changed, int left, int top, int right,
	// int bottom) {
	// super.onLayout(changed, left, top, right, bottom);
	//
	// // 初始化ListView对象
	// if (mListView == null) {
	// getListView();
	// }
	// }
	//
	// /**
	// * 获取ListView对象
	// */
	// private void getListView() {
	// int childs = getChildCount();
	// if (childs > 0) {
	// View childView = getChildAt(0);
	// if (childView instanceof ListView) {
	// mListView = (ListView) childView;
	// mListView.addFooterView(mListViewFooter);
	// // 设置滚动监听器给ListView, 使得滚动的情况下也可以自动加载
	// mListView.setOnScrollListener(this);
	// LogUtil.d("### 找到listview");
	// }
	// }
	// }

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.ViewGroup#dispatchTouchEvent(android.view.MotionEvent)
	 */
	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		final int action = event.getAction();

		switch (action) {
		case MotionEvent.ACTION_DOWN:
			// 按下
			mYDown = (int) event.getRawY();
			break;

		case MotionEvent.ACTION_MOVE:
			// 移动
			mLastY = (int) event.getRawY();
			break;

		case MotionEvent.ACTION_UP:
			// 抬起
			if (canLoad()) {
				loadData();
			}
			break;
		default:
			break;
		}

		return super.dispatchTouchEvent(event);
	}

	/**
	 * 是否可以加载更多, 条件是到了最底部, listview不在加载中, 且为上拉操作.
	 * 
	 * 且当前没有正在刷新数据(下拉刷新). isRefreshing() == true 表示正在下拉刷新 .
	 * SwipeRefreshLayout自带的方法
	 */
	private boolean canLoad() {
		if (!hasListView()) {
			return false;
		}
		// int count = mListView.getAdapter().getCount() - 1;
		int count = getDataCount();
		if (count <= 0) {
			LogUtil.w("RefreshLayout --- 适配器数据个数为0，不执行上拉加载操作！");
			return false;
		}
		LogUtil.v("RefreshLayout --- 数据个数不为空：" + count);
		return isBottom() && !isLoading && isPullUp() && !isRefreshing();
	}

	/**
	 * 判断是否到了最底部
	 */
	private boolean isBottom() {
		if (mListView != null && mListView.getAdapter() != null) {
			// return mListView.getLastVisiblePosition() == (mListView
			// .getAdapter().getCount() - 1);
			return mListView.getLastVisiblePosition() == mListView.getAdapter()
					.getCount() - 1
					&& mListView.getChildAt(mListView.getChildCount() - 1)
							.getBottom() <= mListView.getHeight();
		}
		return false;
	}

	/**
	 * 是否是上拉操作
	 */
	private boolean isPullUp() {
		return (mYDown - mLastY) >= mTouchSlop;
	}

	/**
	 * 如果到了最底部,而且是上拉操作.那么执行onLoad方法
	 */
	private void loadData() {
		if (mOnLoadListener != null) {
			// 设置状态
			setLoading(true);
			//
			mOnLoadListener.onLoad();
		}
	}

	/**
	 * @param loading
	 */
	public void setLoading(boolean loading) {
		isLoading = loading;
		if (isLoading) {
			// mListView.addFooterView(mListViewFooter);
			layFooter.setVisibility(View.VISIBLE); // 11-11修改，为解决部分机型上FC的问题
			tvLoadMore.setVisibility(View.INVISIBLE);
			mListView.setSelection(mListView.getBottom()); // 11-11修改，为解决bug添加
			mRefreshLoading.startLoading(); // 11-11增加
		} else {
			mRefreshLoading.stopLoading(); // 11-11增加
			// mListView.removeFooterView(mListViewFooter);
			layFooter.setVisibility(View.INVISIBLE); // 11-11修改，为解决部分机型上FC的问题
			tvLoadMore.setVisibility(View.VISIBLE);
			mYDown = 0;
			mLastY = 0;
		}
	}

	/**
	 * @param loadListener
	 */
	public void setOnLoadListener(OnLoadListener loadListener) {
		mOnLoadListener = loadListener;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// 11-11 暂时去掉
		// // 滚动时到了最底部也可以加载更多
		// if (canLoad()) {
		// loadData();
		// }
	}

	/**
	 * 加载更多的监听器
	 */
	public static interface OnLoadListener {
		public void onLoad();
	}

	public void setTvLoadMore(boolean hasNoMoreData) {
		tvLoadMore.setVisibility(View.VISIBLE);
		if (hasNoMoreData) {
			tvLoadMore.setText(R.string.base_has_nomore_data);
		} else {
			tvLoadMore.setText(R.string.base_load_more);
		}
	}

	// 当数据个数为0时，隐藏tvLoadMore
	public void setTvDisplay() {
		tvLoadMore.setText(R.string.base_load_more);
		if (hasListView() && hasData()) {
			tvLoadMore.setVisibility(View.VISIBLE);
		} else {
			tvLoadMore.setVisibility(View.INVISIBLE);
		}
	}

	// 是否含有数据
	private boolean hasData() {
		int count = getDataCount();
		return count > 0 ? true : false;
	}

	// 获取数据个数
	private int getDataCount() {
		if (myAdapter != null) {
			return myAdapter.getCount();
		}
		return mListView.getAdapter().getCount() - 1;
	}

	private boolean hasListView() {
		if (mListView == null) {
			LogUtil.e("RefreshLayout --- mListView为空！");
			return false;
		}
		if (mListView.getAdapter() == null) {
			LogUtil.e("RefreshLayout --- mListView未设置adapter！");
			return false;
		}
		return true;
	}

	/**
	 * 11-16添加，为解决因添加headerView或footerView后，数据个数判断错误的情况。
	 * 
	 * 只在getDataCount中使用到。
	 */
	private BaseAdapter myAdapter;

	public void setMyAdapter(BaseAdapter myAdapter) {
		this.myAdapter = myAdapter;
	}

}